﻿<template>
    <div class="esProductChannel-container">
        <el-card shadow="hover">
            <el-form :model="state.queryParams" ref="queryForm" :inline="true">
                <el-form-item :label-width='70' label="商户名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.merchantId"
                               placeholder="请选择" filterable>
                        <el-option v-for='item in state.merchantDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="渠道名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.channelId" placeholder="请选择"
                               filterable>
                        <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="产品名称" prop="name">
                    <el-input placeholder="产品名称" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.productName"/>
                </el-form-item>
                <el-form-item :label-width='70' label="Key" prop="code">
                    <el-input placeholder="Key" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.code"/>
                </el-form-item>
                <el-form-item :label-width='70' label="大Key" prop="productCategoryCode">
                    <el-input placeholder="大Key" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.productCategoryCode"/>
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="state.loading"
                                   v-auth="'esProductChannel:query'">
                            查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'esProductChannel:query'"> 重置
                        </el-button>
                    </el-button-group>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="hover" style="margin-top: 8px">
            <div style="margin: -8px 0 10px 0;">
                <el-button type="success" plain icon="ele-Plus" @click="openAddEsProductChannel"
                           v-auth="'esProductChannel:add'"> 新增
                </el-button>
                <el-button :disabled="state.batchAggregation.length==0" type="primary" icon="ele-Edit" @click="openEditBatch" v-auth="'esProductChannel:add'"> 批量编辑
                </el-button>
            </div>
            <el-table :data="state.data" style="width: 100%" v-loading="state.loading" tooltip-effect="light"
                      row-key="id"
                      border stripe highlight-current-row @selection-change="editAggregation">
                <el-table-column header-align="center" type="selection" width="50" align="center" />
                <el-table-column header-align="center" prop="merchantName" label="商户名称" width="100"
                                 show-overflow-tooltip />
                <el-table-column header-align="center" prop="productName" label="产品名称" min-width="330"
                                 show-overflow-tooltip >
                    <template #default="scope">
						<span :class='productClassObject(Number(scope.row.status))'>
                           {{scope.row.productName}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelName" label="渠道名称" align="center" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="operatorPlatform" label="运营商" align="center" width="90"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <template v-if="scope.row.operatorPlatform !== -1">
                            <el-tag :type="getOperatorTagType(scope.row.operatorPlatform)">
                                {{ getOperatorLabel(scope.row.operatorPlatform) }}
                            </el-tag>
                        </template>
                        <span v-else></span> <!-- 无值时显示空白 -->
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="code" label="Key" show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productCategoryCode" align="center" label="大Key" min-width="80" show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productCategoryIndex" align="center" label="同品排序" min-width="100" show-overflow-tooltip/>
                <el-table-column header-align='center' label="状态" align="center" show-overflow-tooltip width="80">
                    <template #default="scope">
                        <div @click="changeStatus(scope.row)">
                            <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="scope.row.status <= 2 ? 2 : 4"
                                size="small"
                                :style="getSwitchStyle(scope.row.status)"
                                v-auth="'esProductChannel:update'"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="syncUrl" label="同步链接" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="merchantSettlementPrice" label="商户结算(元)" align="right"
                                 width="110"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        {{ (scope.row.merchantSettlementPrice / 100.00).toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelSettlementPrice" label="渠道结算(元)" align="right"
                                 width="110"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        {{ (scope.row.channelSettlementPrice / 100.00).toFixed(2) }}
                    </template>
                </el-table-column>
<!--                <el-table-column header-align="center" prop="dailyLimit" label="日限数量" align="right" width="100"-->
<!--                                 show-overflow-tooltip/>-->
<!--                <el-table-column header-align="center" prop="monthlyLimit" label="月限数量" align="right" width="100"-->
<!--                                 show-overflow-tooltip/>-->
                <el-table-column header-align="center" prop="deductionInterval" label="扣量" align="right" width="100"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.startingQuantity }}起扣{{
                            scope.row.deductionInterval == 0 ? 0 : ((scope.row.deductionNumerator / scope.row.deductionInterval * 1.0) * 100.00).toFixed(0)
                        }}%
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="isLimitIP" label="IP限制" width="80" align="center"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.isLimitIP === 1">启用</el-tag>
                        <el-tag type="info" v-else-if="scope.row.isLimitIP === 2">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="isMutex" label="业务互斥" width="90" align="center"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.isMutex === 1">启用</el-tag>
                        <el-tag type="info" v-else-if="scope.row.isMutex === 2">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="remark" label="备注" min-width="200"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="createTime" label="创建时间" width="160"
                                 show-overflow-tooltip/>
                <el-table-column label="操作" width="170" align="center" fixed="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-button size="small" text type="info" @click="showChannelInfo(scope.row)"
                        > 信息
                        </el-button>
                        <el-button size="small" text type="primary" @click="openEditEsProductChannel(scope.row)"
                                   v-auth="'esProductChannel:update'"> 编辑
                        </el-button>
                        <el-button size="small" text type="danger" @click="delEsProductChannel(scope.row)"
                                   v-auth="'esProductChannel:delete'"> 删除
                        </el-button>
                        <el-button size="small" text type="success" @click="onOpenTestDialog(scope.row)"
                                   v-auth="'esProductChannel:update'"> 测试
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                           :page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                           v-model:page-size="state.queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="state.total"/>
            <EditEsProductChannel ref="editEsProductChannelRef" :title="state.editTitle"/>
            <TestEsProductChannelDialog ref="testEsProductChannelDialogRef" :title="state.editTitle"/>
            <EditBatchEsProductChannel ref="editBatchEsProductChannelRef" :title="state.editTitle"/>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="esProductChannel">

import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {ElMessageBox, ElMessage, ElNotification} from 'element-plus';
import mittBus from '/@/utils/mitt';
// 引入组件
import EditEsProductChannel from '/@/views/exocytosis/operate/productChannel/component/editEsProductChannel.vue';
import TestEsProductChannelDialog from '/@/views/exocytosis/operate/productChannel/component/testEsProductChannel.vue';
import EditBatchEsProductChannel from '/@/views/exocytosis/operate/productChannel/component/editBatchEsProductChannel.vue';

import {EsProductChannel, sysBaseDict} from '/@/api/models';
import SysEsProductChannelApi from '/@/api/exocytosis/productChannel';
import SysEsMerchantApi from '/@/api/exocytosis/merchant';
import SysEsChannelApi from '/@/api/exocytosis/channel';
import {optionDict} from "/@/const/dict";

const editEsProductChannelRef = ref<InstanceType<typeof EditEsProductChannel>>();
const testEsProductChannelDialogRef = ref<InstanceType<typeof TestEsProductChannelDialog>>();
const editBatchEsProductChannelRef = ref<InstanceType<typeof EditBatchEsProductChannel>>();

const state = reactive({
    loading: false,
    data: [] as Array<EsProductChannel>,
    total: 0 as any,
    queryParams: {
        merchantId: undefined,
        channelId: undefined,
        productName: undefined,
        code: undefined,
        productCategoryCode: undefined,
        pageNum: 1,
        pageSize: 20,
    },
    editTitle: '',
    merchantDict: [] as sysBaseDict[],
    channelDict: [] as sysBaseDict[],
    batchAggregation: [] as EsProductChannel[],
});

onMounted(async () => {
    await merchantDictQuery();
    await channelDictQuery();
    mittBus.on('submitRefresh', () => {
        handleQuery();
    });
});

onUnmounted(() => {
    mittBus.off('submitRefresh');
});

// 查询操作
const handleQuery = async () => {
    state.loading = true;
    const res = await SysEsProductChannelApi().queryRecord(state.queryParams);
    state.data = res.data.result.items ?? [];
    state.total = res.data.result?.total;
    state.loading = false;
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize',]; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 数据
    state.data = [];
};

// 打开新增页面
const openAddEsProductChannel = () => {
    state.editTitle = '添加';
    editEsProductChannelRef.value?.openDialog({
        status: 1,
        isLimitIP: 2,
        isMutex: 2,
        merchantSettlementPrice: 0,
        channelSettlementPrice: 0,
        hourlyLimit: 0,
        dailyLimit: 0,
        monthlyLimit: 0,
        startingQuantity: 5,
        deductionInterval: 3,
        deductionNumerator: 1,
        intervalSyncPeriod: 0,
        syncOnlySuccess: 1,
        blackApp: 2,
        productCategoryIndex: 10,
    }, 'add');
};

// 打开编辑页面.
const openEditEsProductChannel = (row: EsProductChannel) => {
    state.editTitle = '编辑';
    editEsProductChannelRef.value?.openDialog(row, 'edit');
};

// 删除
const delEsProductChannel = (row: any) => {
    ElMessageBox.confirm(`确定删除：【${row.code}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            let res = await SysEsProductChannelApi().deletePost({id: row.id});
            if (res.data.resCode != '0000')
                ElMessage.error(res.data.resMessage);
            else
                ElMessage.success("删除成功");
            await handleQuery();
        })
        .catch(() => {
        });
};

const copyToClipboard = async (text: string) => {
    try {
        // 优先使用现代 API
        if (navigator.clipboard?.writeText) {
            await navigator.clipboard.writeText(text);
            // ElMessage.success('信息已复制到剪切板！');
        } else {
            // 回退方案
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            // ElMessage.success('信息已复制到剪切板！');
        }
    } catch (err) {
        ElMessage.error('信息复制失败，请手动复制');
    }
};

const showChannelInfo = async (row: EsProductChannel) => {
    try {
        const res = await SysEsProductChannelApi().queryCodeInfo({ id: row.id });

        if (res.data.resCode !== "0000") {
            ElMessage.error(res.data.resMessage);
            return;
        }

        const textToCopy = res.data.resMessage;
        const notificationTitle = `${row.productName} 配给 ${row.channelName}`;

        // 显示通知（带 el-button 复制按钮）
        const notification = ElNotification({
            title: notificationTitle,
            message: `
                        <div class="custom-notification">
                          <div class="notification-actions">
                            <el-button
                              class="copy-btn"
                              type="primary"
                              size="small"
                            >
                              复制信息
                            </el-button>
                          </div>
                          <div class="notification-content">${textToCopy.replaceAll("\n", "<br>")}</div>
                        </div>
                      `,
            dangerouslyUseHTMLString: true,
            duration: 3000,
            customClass: 'enhanced-notification'
        });

        // 动态绑定复制逻辑
        setTimeout(() => {
            const copyBtn = document.querySelector('.copy-btn');
            if (copyBtn) {
                copyBtn.addEventListener('click', async () => {
                    try {
                        await copyToClipboard(textToCopy);
                        notification.close();
                        ElMessage.success('复制成功！');
                    } catch (err) {
                        ElMessage.error('复制失败，请手动复制');
                    }
                });
            }
        }, 100);

    } catch (apiError) {
        ElMessage.error("获取渠道信息失败");
    }
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 商户列表
const merchantDictQuery = async () => {
    await SysEsMerchantApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.merchantDict = res.data.result ?? [];
    });
};

// 渠道列表
const channelDictQuery = async () => {
    await SysEsChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};

// 测试弹窗
const onOpenTestDialog = (row: EsProductChannel) => {
    testEsProductChannelDialogRef.value?.openDialog(row);
};

// 修改状态
const changeStatus = (row: EsProductChannel) => {
    let onStatus = row.status == 1 ? '一键启动' : row.status == 2 ? '一键关停' : '';
    row.status = row.status == 1 ?  1 : 4;
    ElMessageBox.confirm(`是否${onStatus}（涉及到：次日计划 -> 当日计划）？`, '', {
            title: '提示',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            SysEsProductChannelApi()
                .setStatusPost(row)
                .then((res) => {
                    if (res.data.resCode == '0000') {
                        ElMessage.success(`${onStatus}状态设置成功`);
                    } else {
                        row.status = row.status == 1 ? 2 : 1;
                        ElMessage.error(`${onStatus}状态设置失败`);
                    }
                })
                .catch(() => {
                    row.status = row.status == 1 ? 2 : 1;
                });
        })
        .catch(() => {
            row.status = row.status == 1 ? 2 : 1;
        })
};

// 获取运营商标签文本
const getOperatorLabel = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.label || '未知'
}

// 获取标签类型
const getOperatorTagType = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.type || 'danger'
}

const getSwitchStyle = (status) => {
    return status <= 2
        ? '--el-switch-on-color: #67C23A; --el-switch-off-color: red'
        : '--el-switch-on-color: #67C23A; --el-switch-off-color: #E6A23C';
};

// 批量修改
const openEditBatch = () => {
    state.editTitle = '批量修改';
    editBatchEsProductChannelRef.value?.openDialog(state.batchAggregation);
}

// 选中的参数赋值给 batchAggregation
const editAggregation = (list: EsProductChannel[]) => {
    // console.log("editAggregation >>> "+JSON.stringify(list));
    state.batchAggregation = list;
};

const productClassObject = (status: number) => {
    let colorClass = '';
    if (status === 2 || status === 4) {
        colorClass = 'text-info';
    }
    return colorClass;
};
</script>

<style>
/* 全局或组件样式 */
:deep(.enhanced-notification)  {
    width: 90vw; /* 限制宽度适应手机屏幕 */
    max-width: 600px;
}

.custom-notification {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.notification-content {
    line-height: 1.6;
    word-break: break-word; /* 长文本自动换行 */
}

.notification-actions {
    display: flex;
    justify-content: flex-end; /* 强制右对齐 */
    width: 100%;
}

/* 覆盖 el-button 样式 */
.copy-btn {
    margin-left: auto; /* 双保险右对齐 */
    color: var(--el-color-primary);
    border: none;
}

/* 移动端优化 */
@media (max-width: 768px) {
    .enhanced-notification {
        width: 85vw;
    }
    .copy-btn {
        padding: 8px 16px; /* 增大点击区域 */
        font-size: 14px; /* 文字放大 */
    }
}
</style>

<style scoped lang='scss'>
.text-primary {
    color: var(--el-color-primary);
}

.text-success {
    color: var(--el-color-success);
}

.text-info {
    color: var(--el-color-info);
}

.text-warning {
    color: var(--el-color-warning);
}

.text-danger {
    color: var(--el-color-danger);
}
</style>
